package com.mindata.blockchain.socket.server;

import java.io.IOException;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.tio.server.AioServer;
import org.tio.server.ServerGroupContext;
import org.tio.server.intf.ServerAioHandler;
import org.tio.server.intf.ServerAioListener;

import com.mindata.blockchain.common.AppId;
import com.mindata.blockchain.common.CommonUtil;
import com.mindata.blockchain.core.bean.Member;
import com.mindata.blockchain.core.bean.MemberData;

/**
 * server启动器
 *
 * @author wuweifeng wrote on 2018/3/12.
 */
@Component
public class BlockServerStarter {
	@Resource
	private RestTemplate restTemplate;
	@Value("${managerUrl}")
	private String managerUrl;
	@Value("${appId}")
	private String appId;
	@Value("${name}")
	private String name;

	@PostConstruct
	public void serverStart() throws IOException {
		final ServerAioHandler serverAioHandler = new BlockServerAioHandler();
		final ServerAioListener serverAioListener = new BlockServerAioListener();
		final ServerGroupContext serverGroupContext = new ServerGroupContext(serverAioHandler, serverAioListener);
		final AioServer aioServer = new AioServer(serverGroupContext);

		final String localIp = CommonUtil.getLocalIp();
		//本机启动服务
		final MemberData memberData = restTemplate
				.getForEntity(managerUrl + "member/appId?name=" + name + "&appId=" + AppId.value + "&ip=" + localIp,
						MemberData.class)
				.getBody();

		//合法的客户端
		if (memberData.getCode() == 0) {
			final List<Member> memberList = memberData.getMembers();

			aioServer.start(null, memberList.get(0).getSocketPort());
		}
		//		aioServer.start(null, Const.PORT);
	}
}
